package com.thwcompany.rabbitMQ.listener;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
/**
 * @program: springboot-rabbit-mq
 * @author: tenghw
 * @create: 2024-01-27 15:05
 * @Version 1.0
 * @description: 消费者接收延迟消息
 **/
@Component
@Slf4j
public class DelayReceiver {
    @RabbitListener(queues = "delayed.queue")
    public void receiveDelayedMessage(String msg , Channel channel, Message message) throws IOException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        //String msg1 = new String(message.getBody());
        log.info("当前时间：{}，消费者收到延迟队列的消息：{}", LocalDateTime.now().format(formatter), msg);
        //log.info("当前时间：{}，消费者收到延迟队列的消息：{}",  LocalDateTime.now().format(formatter), msg1);

        //消费者1号进行手工确认签收消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.println("消费者要签收的延迟消息的deliveryTag："+deliveryTag);
        try {
            channel.basicAck(deliveryTag,false);
            System.out.println("消费者要签收的延迟消息成功！");
        } catch (Exception e) {
            // 处理消息处理失败的情况
            //channel.basicRecover();
            channel.basicNack(deliveryTag, false, true);
            e.printStackTrace();
        }
    }
}